# -*- coding: utf8 -*-

import traceback
from time import sleep
import mimetypes
import magic

import fnmatch
import os

from worker import Worker
from archive import is_supported
from service.hash import HashRequest

class FileListWorker( Worker ):

    my_query_name = "files"

    def get_mime_type( self, mo, full_path ):
        mime = None
        try:
            mime = mo.from_file( full_path )
        except:
            pass
        if not mime:
            mime = mimetypes.guess_type( full_path )[0]
        if not mime:
            mime = "application/octet-stream"
        return mime

    def run ( self ):
        
        print("FileListWorker: START: %s" % self.my_query_name)
        
        mimetypes.init()
        mimetypes.add_type( "application/x-rar", ".rar" )
        mimetypes.add_type( "application/x-rar", ".cbr" )
        mimetypes.add_type( "application/zip", ".cbz" )
        mimetypes.add_type( "application/x-7z-compressed", ".7z" )
        mimetypes.add_type( "application/x-7z-compressed", ".cb7" )
        mimetypes.add_type( "application/x-tar", ".cbt" )
        mimetypes.add_type( "application/x-tar", ".cbg" )
        mimetypes.add_type( "application/x-tar", ".cbb" )
        
        mage = magic.open( magic.MAGIC_MIME_TYPE )
        mage.load()
        
        p = self.app.get_project()
        sess = p.get_session()

        hash_request = HashRequest()
        
        while not self.stop_event.isSet():

            try:
                data = self.app.get_queue(self.my_query_name).get_nowait()
            except:
                data = None

            if data is None:
                sleep(0.01)
                continue

            parent_id, parent_path, name = data
            
            full_path = os.path.join(parent_path, name)
            if not os.path.isfile(full_path):
                self.app.get_queue(self.my_query_name).task_done()
                continue

            self.app.get_stats().inc("files_count", 1)

            match = False
            lpath = full_path.lower()
            for ptrn in self.app.get_option("filter_in"):
                if fnmatch.fnmatchcase(lpath, ptrn.lower()):
                    match = True
                    break
            for ptrn in self.app.get_option("filter_out"):
                if fnmatch.fnmatchcase(lpath, ptrn.lower()):
                    match = False
                    break
            

            if match:

                self.app.get_stats().inc("files_filtered", 1)

                st = os.lstat( full_path )

                try:
                    fsize = os.path.getsize( full_path )
                    mtime = os.path.getmtime( full_path )
                    mime = self.get_mime_type( mage, full_path )
                    fitem = p.insert_file( parent_id, st.st_dev, mime, fsize, mtime, name )

                    self.app.get_stats().inc("files_size", fsize )

                    fid = fitem.id
                    sess.expunge( fitem )
                    self.app.poll_hash_service(st.st_dev)
                    hash_request.hash( fid, st.st_dev, fsize, full_path )

                    if is_supported(mime):
                        self.app.get_stats().inc("archives_count", 1)
                        self.app.get_archive_queue("archives", 0).put_nowait( ( fid, full_path, mime ) )

                except Exception, e:
                    self.app.get_stats().inc("errors_count", 1)
                    print("FileListWorker: ERROR!\n%s" % traceback.format_exc())
                    pass

            self.app.get_queue(self.my_query_name).task_done()
        
        print("FileListWorker: STOP: %s" % self.my_query_name)

        p.close_session()

        self.stop_event.clear()
        return
